import { quote } from '@satorijs/element/jsx-runtime';
import { Context, Schema, Session, h } from 'koishi';

export const name = 'auto-reply';

export const AUTO_REPLY_MODES = {
  CONTAINS: '包含子串',
  STARTS_WITH: '包含子串且开头',
  ENDS_WITH: '包含子串且结尾',
  EQUALS: '严格等于',
} as const;

export type AutoReplyMode = typeof AUTO_REPLY_MODES[keyof typeof AUTO_REPLY_MODES];

export interface Config {
  enablePlusOne: boolean;
  plusOneThreshold: number; 
  plusOneBlackList: string[];
  quoteWhenPlusOne: boolean;
  addPlusOnePrefix: boolean;

  enableAutoRepeat: boolean;
  autoRepeatConfig: {
    keyword: string;
    mode: AutoReplyMode
    quoteWhenRepeat: boolean;
  }[];

  enableAtBotReply: boolean;
  atBotReplyKeyword: string;

  enableAutoReply: boolean;
  // autoReplyConfig: {
  //   keywordList: string[];
  //   replyList: string[];
  // }[];
  autoReplyConfig: {
    keywordList: {
      keyword: string;
      mode: AutoReplyMode;
    }[];
    replyList: string[];
  }[];

}

// 我想给所有的description都加点emoji
export const Config: Schema<Config> = Schema.intersect([
  Schema.object({
    enablePlusOne: Schema.boolean()
      .default(true)
      .description('⚡ 是否启用 +1 功能'),
    plusOneBlackList: Schema.array(Schema.string())
      .default(["干什喵"])
      .description('🔄 自动+1 时需要排除的关键词'),
    plusOneThreshold: Schema.number()
      .default(2) 
      .description('🔢 在群聊中达到多少条相同消息时自动 +1。例如，设置为2表示群聊内连续发送2条相同消息时触发'),
    quoteWhenPlusOne: Schema.boolean()
      .default(true)
      .description('🔄 是否在 +1 时引用原消息'),
    addPlusOnePrefix: Schema.boolean()
      .default(true)
      .description('🔄 是否在 +1 时添加【+1】前缀'),
  }).description("🔄 自动+1"),

  Schema.object({
    enableAutoRepeat: Schema.boolean()
      .default(true)
      .description('🎯 是否启用自动复读功能'),
    autoRepeatConfig: Schema.array(Schema.object({
      keyword: Schema.string()
        .description('🔑 自动复读的关键词'),
      mode: Schema.union([
        AUTO_REPLY_MODES.CONTAINS,
        AUTO_REPLY_MODES.STARTS_WITH,
        AUTO_REPLY_MODES.ENDS_WITH,
        AUTO_REPLY_MODES.EQUALS,
      ])
        .description('⚙️ 自动复读的模式'),
      quoteWhenRepeat: Schema.boolean()
        .default(true)
        .description('🔄 是否引用(回复)'),
    }))
      .role('table')
      .default([
        { keyword: 'qwq', mode: AUTO_REPLY_MODES.EQUALS, quoteWhenRepeat: true },
        { keyword: 'awa', mode: AUTO_REPLY_MODES.EQUALS, quoteWhenRepeat: true },
        { keyword: 'ovo', mode: AUTO_REPLY_MODES.EQUALS, quoteWhenRepeat: true },
        { keyword: '喵', mode: AUTO_REPLY_MODES.EQUALS, quoteWhenRepeat: true },
      ])
      .description('📝 自动复读的配置'),
  }).description("🔁 自动复读"),

  Schema.object({
    enableAtBotReply: Schema.boolean()
      .default(true)
      .description('🤖 是否启用 @bot 回复功能'),
    atBotReplyKeyword: Schema.string()
      .default('我喜欢你')
      .description('💭 @bot 回复的关键词'),
  }).description("🤖 @bot 回复"),

  // Schema.object({
  //   enableAutoReply: Schema.boolean()
  //     .default(true)
  //     .description('💬 是否启用自动回复功能'),
  //   autoReplyConfig: Schema.array(Schema.object({
  //     keywordList: Schema.array(Schema.string())
  //       .role('table')
  //       .description('📑 自动回复的关键词列表'),
  //     replyList: Schema.array(Schema.string())
  //       .role('table')
  //       .description('📝 自动回复的内容列表'),
  //   }))
  //     .role('table')
  //     .default([
  //       { keywordList: ['早上好', '早', '早安'], replyList: ['早上好喵'] },
  //       { keywordList: ['中午好', '午好', '午安'], replyList: ['中午好喵'] },
  //       { keywordList: ['下午好'], replyList: ['下午好喵'] },
  //       { keywordList: ['晚上好'], replyList: ['晚上好喵'] },
  //       { keywordList: ['晚安', '睡了'], replyList: ['晚安喵'] },
  //       { keywordList: ['原神启动', '原神'], replyList: ['玩原神玩的'] },
  //     ])
  //     .description('📋 自动回复的配置'),
  // }).description("💬 自动回复"),

  Schema.object({
    enableAutoReply: Schema.boolean()
      .default(true)
      .description('💬 是否启用自动回复功能'),
    autoReplyConfig: Schema.array(Schema.object({
      keywordList: Schema.array(
        Schema.object({
          keyword: Schema.string()
            .description('关键词'),
          mode: Schema.union([
            AUTO_REPLY_MODES.CONTAINS,
            AUTO_REPLY_MODES.STARTS_WITH,
            AUTO_REPLY_MODES.ENDS_WITH,
            AUTO_REPLY_MODES.EQUALS,
          ])
            .description('匹配模式'),
        })
      )
        .role('table')
        .description('📑 自动回复的关键词列表'),
      replyList: Schema.array(Schema.string())
        .role('table')
        .description('📝 自动回复的内容列表'),
    }))
      .role('table')
      .default([
        { 
          keywordList: [ { keyword: '早上好', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '早', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '早安', mode: AUTO_REPLY_MODES.EQUALS } ], 
          replyList: ['早上好喵'] 
        },
        { 
          keywordList: [ { keyword: '下午好', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '下午', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '下午好', mode: AUTO_REPLY_MODES.EQUALS }], 
          replyList: ['下午好喵'] 
        },
        { 
          keywordList: [ { keyword: '晚上好', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '晚上', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '晚上好', mode: AUTO_REPLY_MODES.EQUALS } ], 
          replyList: ['晚上好喵'] 
        },
        { 
          keywordList: [ { keyword: '晚安', mode: AUTO_REPLY_MODES.EQUALS }, { keyword: '睡了', mode: AUTO_REPLY_MODES.EQUALS } ], 
          replyList: ['晚安喵'] 
        },

      ])
      .description('📋 自动回复的配置'),
  }).description("💬 自动回复"),

]);


const guildMessageQueues = new Map<string, string[]>();

export function apply(ctx: Context, config: Config) {
  if ( config.enablePlusOne )
    ctx.on('message', async(session: Session) => {
      if (!session.guildId || !session.content) return;
      if (session.bot.selfId === session.userId) return;

      let messageQueue = guildMessageQueues.get(session.guildId);
      if (!messageQueue) {
        messageQueue = []; 
        guildMessageQueues.set(session.guildId, messageQueue);
      }
      messageQueue.push(session.content);
      while (messageQueue.length > config.plusOneThreshold)
        messageQueue.shift(); // 去掉队头

      if ( config.plusOneBlackList.some(keyword => session.content.includes(keyword)) )
        return;

      const allMsgAreSame = (messageQueue.length === config.plusOneThreshold) &&
        (messageQueue.every(msg => msg === messageQueue[0]));
      if (allMsgAreSame) {
        // 如果所有消息都相同且达到阈值，则复读
        let msg = "";
        if ( config.quoteWhenPlusOne ) msg += `${h.quote(session.messageId)}`;
        if ( config.addPlusOnePrefix ) msg += `【+1】 `;
        msg += `${session.content}`;
        await session.send(msg);
        // 发送 "+1" 后，清空该群组的消息队列
        // 这样可以防止在复读后，下一次相同消息再次立即触发复读
        guildMessageQueues.set(session.guildId, []);
      }

      return;
    });
  
  if ( config.enableAutoRepeat ) 
    ctx.on('message', async(session: Session) => {
      if (!session.content) return;
      const { content } = session;

      // const hit: boolean = config.autoRepeatConfig.some(item => {
      //   const { keyword, mode } = item;
      //   if (mode === AUTO_REPLY_MODES.CONTAINS) 
      //     return content.includes(keyword);
      //   if (mode === AUTO_REPLY_MODES.STARTS_WITH) 
      //     return content.startsWith(keyword);
      //   if (mode === AUTO_REPLY_MODES.ENDS_WITH) 
      //     return content.endsWith(keyword);
      //   if (mode === AUTO_REPLY_MODES.EQUALS) 
      //     return content === keyword;
      // })

      // if (hit) await session.send(`${h.quote(session.messageId)}${content}`);

      // 找出第一个匹配项
      const matchedItem = config.autoRepeatConfig.find(item => {
        const { keyword, mode } = item;
        if (mode === AUTO_REPLY_MODES.CONTAINS) 
          return content.includes(keyword);
        if (mode === AUTO_REPLY_MODES.STARTS_WITH) 
          return content.startsWith(keyword);
        if (mode === AUTO_REPLY_MODES.ENDS_WITH) 
          return content.endsWith(keyword);
        if (mode === AUTO_REPLY_MODES.EQUALS) 
          return content === keyword;
        return false;
      });

      if (matchedItem) {
        const { quoteWhenRepeat } = matchedItem;
        const quote = quoteWhenRepeat ? h.quote(session.messageId) : '';
        await session.send(`${quote}${content}`);
  }
    })
  
  if ( config.enableAtBotReply )
    ctx.on('message', async(session: Session) => {
      // 有人艾特bot咩？
      const includeAtBot = session.event.message.elements
        .some(e => e.type === 'at' && e.attrs.id === session.selfId);
      // 包含关键词咩?
      const inclueKeyword = session.event.message.content
        .includes(config.atBotReplyKeyword);
      
      if (includeAtBot && inclueKeyword )
        await session.send(h.quote(session.messageId) + config.atBotReplyKeyword);
    })

  if ( config.enableAutoReply )
    ctx.on('message', async(session: Session) => {
      const firstHitItem = config.autoReplyConfig.find(item => 
        item.keywordList.some(keyword => {
          const { keyword: kw, mode } = keyword;
          if (mode === AUTO_REPLY_MODES.CONTAINS) 
            return session.content.includes(kw);
          if (mode === AUTO_REPLY_MODES.STARTS_WITH) 
            return session.content.startsWith(kw);
          if (mode === AUTO_REPLY_MODES.ENDS_WITH) 
            return session.content.endsWith(kw);
          if (mode === AUTO_REPLY_MODES.EQUALS) 
            return session.content === kw;
          return false;
        })
      );
      if (firstHitItem) {
        const randomIdx = Math.floor(Math.random() * firstHitItem.replyList.length);
        await session.send(h.quote(session.messageId) + firstHitItem.replyList[randomIdx]);
      }
    })

}